<template>
  <el-container class="main">
    <el-header class="clearfix">
      <router-link active-class="active" to="/index" class="logo leftfix">
        <el-image
          style="width: 60px; height: 30px"
          :src="logo"
          fit="contain"
        ></el-image>
        <span>{{ logoTitle }}</span>
      </router-link>

      <el-form class="search leftfix">
        <el-form-item>
          <el-input
            placeholder="请输入内容"
            v-model="queryParams.name"
            :clearable="true"
            class="input-with-select"
            @keyup.enter.native="handleQuery"
          >
            <el-select
              v-model="queryParams.classificationId"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option label="未选择" value=""></el-option>
              <el-option
                v-for="item in inputSearchOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="handleQuery()"
            ></el-button>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="goshop leftfix">
        <el-button
          type="warning"
          icon="el-icon-shopping-cart-full"
          round
          @click="handleShop"
          >我的购物车</el-button
        >
      </div>
      <!-- 登录与注册 -->
      <div class="login rightfix">
        <div v-if="loginBefore">
          <span @click="handleOpenLogin">登录</span><span>注册</span>
        </div>

        <div v-if="loginAfter">
          <span>用户：{{ number.account }}</span
          ><span>积分：{{ number.integral }}</span>
        </div>
      </div>
    </el-header>
    <el-main class="clearfix">
      
      <div
        class="leftfix"
        v-for="(item, index) in products"
        :key="item.id"
        :offset="index > 0 ? products : 0"
      >
        <good-card
          :addCommodity="addCommodity"
          :item="item"
          :submitForm="submitForm"
        ></good-card>
      </div>
    </el-main>

    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-table
        v-loading="loading"
        :data="cartList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="购物车编号"
          align="center"
          key="uuid"
          prop="uuid"
          v-if="false"
        />
        <el-table-column
          label="图片"
          align="center"
          key="picture"
          prop="picture"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scopephoto">
            <image-preview
              style="width: 80px; height: 80px"
              :src="scopephoto.row.picture"
            />
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" key="name" prop="name" />
        <el-table-column label="价格" align="center" key="price" prop="price">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-input-number
              class="number"
              v-model="scope.row.commodityNum"
              controls-position="right"
              :min="1"
              :max="100"
            ></el-input-number>
            <span>{{querityFormat(scope.row.qualityUnit)}}</span>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <ul v-if="showStatus" class="clearfix all-item">
          <!-- 积分抵扣 -->
          <li class="leftfix">
            <el-switch v-if="loginAfter" v-model="deductionStatus" active-text="积分抵扣">
            </el-switch>
          </li>
          <!-- 可获得积分 -->
          <li class="leftfix">
            <el-tooltip
              content="登录支付可获得积分（1元=1积分）"
              placement="top"
            >
              <i class="el-icon-question"></i>
            </el-tooltip>
            <span>积分值：{{ sum }}</span>
          </li>

          <li class="leftfix">
            <span
              >合计：<span class="yuan">&yen;&nbsp;{{ sum }}</span> 元</span
            >
          </li>

          <li v-if="deductionStatus" class="leftfix">
            <span
              >抵扣价：<span class="yuan"
                >&yen;&nbsp;{{ deductionAfter }}</span
              ></span
            >
          </li>
        </ul>
        <el-button v-if="showStatus" type="danger" @click="submitForm()"
          >去支付</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 登录会话框 -->

    <el-dialog
      :title="loginTitle"
      :visible.sync="loginOpen"
      width="500px"
      append-to-body
    >
      <div class="form-login">
        <el-form
          ref="form"
          :model="formlogin"
          :rules="rules"
          :inline="true"
          label-width="80px"
        >
          <el-form-item label="会员账号" prop="account">
            <el-input
              v-model="formlogin.account"
              placeholder="请输入会员账号"
            />
          </el-form-item>
          <el-form-item label="会员密码" prop="password">
            <el-input
              v-model="formlogin.password"
              type="password"
              placeholder="请输入密码"
            />
          </el-form-item>
          <el-form-item class="clearfix login-item">
            <el-button
              class="leftfix"
              type="primary"
              @click="loginNUmber"
              :loading="loading"
            >
              <span v-if="!loading">登 录</span>
              <span v-else>登 录 中...</span></el-button
            >

            <el-button
              class="leftfix"
              type="success"
              @click="loginRegister"
              :loading="loading"
            >
              <span v-if="!loading">注册</span>
              <span v-else>注 册 中...</span></el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { goodListCommodity } from "@/api/supermarket/commodity";
import { listNumber, addNumber, updateNumber } from "@/api/supermarket/number";

import { toAliPay } from "@/api/supermarket/order";
import GoodCard from "@/views/supermarket/goodCard";
import { listNameClassification } from "@/api/supermarket/classification";
import logoImg from "@/assets/logo/logo.png";
export default {
  name: "ProductList",
  dicts: ['commodity_quality_unit'],
  components: { GoodCard },
  data() {
    return {
      //登录会话框
      loginTitle: "",
      // 是否开启
      loginOpen: false,
      //登录表单数据
      formlogin: {
        supermarketId: "",
        account: "",
        password: "",
      },
      //登录加载状态
      loading: false,
      // 登录状态
      loginBefore: true,
      loginAfter: false,
      //显示购物统计信息
      showStatus: false,
      //积分抵扣状态
      deductionStatus: false,
      //抵扣之后的值
      deductionAfter: 0,
      // 会员
      number: '',
      //
      // 商品列表
      products: [],
      //加载loading
      loading: false,
      // logo 标题
      logoTitle: "超市商城",
      // logo 图片
      logo: logoImg,
      // 价格合计
      totals: [],
      //搜索框
      inputSearchOptions: [],

      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 是否显示弹出层
      open: false,
      // 购物车表格数据
      cartList: [],
      // 购物车提交后台数据
      trade: {
        statusIntegral: "1",
        number: undefined,
        body: undefined,
        subject: undefined,
        totalAmount: 0,
        supermarketId: undefined,
        commodityList: undefined,
        orderNum: 0,
      },

      // 弹出层标题
      title: "",

      // 请求参数
      queryParams: {
        classificationId: "",
        name: "",
      },
      url: "",
      // 新窗口的引用
      newWin: null,

      //校验规则
      rules: {
        supermarketId: [
          { required: true, message: "账号不能为空", trigger: "blur" },
        ],
        account: [{ required: true, message: "账号不能为空", trigger: "blur" }],
        password: { required: true, message: "密码不能为空", trigger: "blur" },
      },
    };
  },

  created() {
    this.getList();
    this.getGoodClassification();
  },
  computed: {
    sum: {
      get() {
        let sum = 0;
        this.totals.forEach((item) => (sum += item));
        return this.toDecimal2(sum);
      },
      set(value) {
        this.deductionAfter = this.toDecimal2(value);
      },
    },
  },
  watch: {
    url(newVal, oldVal) {
      if (newVal && this.newWin) {
        this.newWin.sessionStorage.clear();
        this.newWin.location.href = newVal;
        // 重定向后把url和newWin重置
        this.url = "";
        this.newWin = null;
      }
    },

    // 选中数据，则显示购物统计信息
    sum: {
      deep: true,
      handler(newVal, oldVal) {
        if (oldVal == 0.00) {
          this.showStatus = false;
        }
        this.showStatus = true;
      },
    },
    deductionStatus(newVal, oldVal) {
      if (newVal) {
        let integral = this.number.integral;
        this.sum = this.sum - integral / 100;
      }
    },
  },
  methods: {
    //获取所有商品
    getList() {
      this.loading = true;
      goodListCommodity(this.queryParams).then((response) => {
        this.products = response.data;
        this.loading = false;
      });
    },

    //制保留2位小数，如：2，会在2后面补上00.即2.00
    toDecimal2(x) {
      var f = parseFloat(x);
      if (isNaN(f)) {
        return false;
      }
      var f = Math.round(x * 100) / 100;
      var s = f.toString();
      var rs = s.indexOf(".");
      if (rs < 0) {
        rs = s.length;
        s += ".";
      }
      while (s.length <= rs + 2) {
        s += "0";
      }
      return s;
    },

    //获取所有商品分类名称
    getGoodClassification() {
      listNameClassification(this.queryParams).then((response) => {
        this.inputSearchOptions = response.data;
      });
    },
    // 质量字典翻译
    querityFormat(qualityUnit) {
   return this.selectDictLabel(this.dict.type.commodity_quality_unit, qualityUnit);
},
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    // 保存商品到购物车
    addCommodity(addObj) {
      this.cartList.unshift(addObj);
    },

    handleShop() {
      this.open = true;
      this.title = "我的购物车";
    },

    /**打开登录框 */
    handleOpenLogin() {
      this.loading = true;
      this.loginTitle = "登录与注册";
      this.loginOpen = true;
      this.loading = false;
    },

    /**
     * 会员登录
     */
    loginNUmber() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          listNumber(this.formlogin).then((response) => {
            this.$modal.msgSuccess("登录成功");
            this.loginBefore = false;
            this.loginAfter = true;
            this.number = response.rows[0];
            this.loginOpen = false;
          });
        }
      });
    },

    /**
     *  注册
     * @param {} value
     * @param {*} data
     */
    loginRegister() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.formlogin.supermarketId = this.products[0].supermarketId;
          addNumber(this.formlogin).then((response) => {
            this.$modal.msgSuccess("注册成功");
            this.loginOpen = false;
          });
        }
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.uuid;
      this.handleQuery();
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.totals = selection.map(
        (item) => item.commodityNum * parseFloat(item.price)
      );
      this.ids = selection.map((item) => item.uuid);

      this.trade.commodityList = selection;
      this.trade.orderNum = selection.length;
      this.trade.totalAmount = this.sum;
      this.trade.subject = selection[0].name;
      this.trade.supermarketId = selection[0].supermarketId;
      this.trade.body = selection[0].name;

      this.trade.number = this.number.numberId;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const uuids = row.uuid || this.ids;
      this.$confirm(
        '是否确认删除商品名称为"' + row.name + '"的数据项?',
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.cartList = this.cartList.filter((carts) => carts.uuid !== uuids);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    /** 提交按钮 */
    submitForm: function (trade) {
      if (this.loginBefore == true) {
        this.$confirm(
          "当前未登录，是否继续支付（登录支付即可获取积分）",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            this.loading = true;
            // 先打开一个空的新窗口，再请求
            this.newWin = window.open();
            let url = "";
            if (/(Android)/i.test(navigator.userAgent)) {
              // 判断是否为Android手机
              url = "toPayAsWeb";
            } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
              // 判断是否为苹果手机
              url = "toPayAsWeb";
            } else {
              url = "toPayAsPC";
            }
            if (trade != null) {
              trade.number = 0;
             // 开启后端接口访问
              toAliPay(url, trade)
                .then((res) => {
                  this.loading = false;
                  this.url = res;
                })
                .catch((err) => {
                  this.loading = false;
                  console.log(err.response.data.message);
                });
              return;
            }
            //  如果会员没有登录，则会员为空，则赋值0传人后端，后端根据0判断是否是匿名会员
            if (this.number == '') {
              // 0 代表匿名用户
              this.trade.number = 0;    
            }// trade 表示商品信息
            toAliPay(url, this.trade)
              .then((res) => {
                this.loading = false;
                this.url = res;
              })
              .catch((err) => {
                this.loading = false;
                console.log(err.response.data.message);
              });
          })
          .catch(() => {
            this.open = false;
            this.$message({
              type: "info",
              message: "已取消",
            });
          });
        return;
      }

      this.loading = true;
      // 先打开一个空的新窗口，再请求
      this.newWin = window.open();
      let url = "";
      if (/(Android)/i.test(navigator.userAgent)) {
        // 判断是否为Android手机
        url = "toPayAsWeb";
      } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        // 判断是否为苹果手机
        url = "toPayAsWeb";
      } else {
        url = "toPayAsPC";
      }     

      if (trade != null) {
        trade.number = this.number.numberId;
        trade.statusIntegral ="1";

        toAliPay(url, trade)
          .then((res) => {
            this.loading = false;
            this.url = res;
          })
          .catch((err) => {
            this.loading = false;
            console.log(err.response.data.message);
          });
        return;
      }
      if (this.deductionStatus) {
        this.trade.totalAmount = this.deductionAfter;
        this.trade.statusIntegral = "0";
      }
      toAliPay(url, this.trade)
        .then((res) => {
          this.loading = false;
          this.url = res;
        })
        .catch((err) => {
          this.loading = false;
          console.log(err.response.data.message);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.main {
  background-color: #e9eef3;
}

// 左浮动
.leftfix {
  float: left;
}
//右浮动
.rightfix {
  float: right;
}
// 清除浮动
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}
.el-header {
  background-color: white;
  height: 50px;
  line-height: 60px;
  color: #333;
  text-align: center;
  padding: auto 0;
  border-radius: 2px;
  margin-top: 5px;
  margin-left: 200px;
  margin-right: 200px;
  margin-bottom: 1px;
  position: sticky;
  z-index: 1;
}

.logo {
  margin-right: 100px;
}

.search {
  margin-top: 10px;
  width: 450px;
}
.search .el-select {
  width: 130px;
}

.form-login {
  padding-left: 80px;
}

.form-login .login-item {
  padding-left: 92px;
}
.goshop {
  margin-left: 60px;
}
.el-select {
  width: 130px;
}

.login span {
  padding-right: 3px;
  margin-right: 5px;
  cursor: pointer;
  border-right: solid 1px black;
}

.login span:last-child {
  border-right: 0;
}

.el-main {
  background-color: white;
  color: #333;
  height: 700px;
  text-align: center;
  margin-top: 1px;
  margin-left: 200px;
  margin-right: 200px;
  // padding-left: 100px;
  //position: relative;
}

.oderList {
  display: inline-block;
}

.all-item {
  list-style-type: none;
}
.all-item li {
  margin-right: 20px;
}
.all-item li .yuan {
  color: red;
}
</style>